function varargout=datalogbinning(data, np)
% DATALOGBINNING Read data and do logarithmic binning
% typically input DATA is a matrix that has 3 columns (q,Intensity,errorbar)
% ******************************
% Input arguments: 
% 1st: data(column1 column2 column3) 
% 2nd: np -> number of final points
%*******************************
% Output arguments: (after binning)
% 1st: xdata
% 2nd: ydata
% 3rd: ydata_err
% ******************************
% Wenjie Wang @ Ames Laboratory 
% version 1.0 (Aug-26-2014)
% ******************************
% Using Matlab function logspace(...) which give boundaries of bins

[nr,nc]=size(data); % nr -> number of rows; nc -> number of columns
if nr<np || nc~=3
    disp('Input is not correct')
    varargout{1}=data;
    return;
end

x=data(:,1);
y=data(:,2);
yerr=data(:,3);

xmin=min(x);
xmax=max(x);
nbinedge=np+1; % np is the bin number, nbinedge is the number of bin edge number
if xmin>0
    xbin=logspace(log10(xmin),log10(xmax),nbinedge);
else
    disp('Negative values-> failure to use logspace(.)');
    return;
end

x_new=zeros(np,1);
y_new=zeros(np,1);
yerr_new=zeros(np,1);


temp_x=[x(1)];
temp_y=[y(1)];
temp_yerr_sq=[yerr(1)^2];
ptr_bin=1;
for k=2:nr
    if xbin(ptr_bin)<=x(k) && x(k)<=xbin(ptr_bin+1)
    temp_x=[temp_x,x(k)];
    temp_y=[temp_y,y(k)];
    temp_yerr_sq=[temp_yerr_sq,yerr(k)^2];
    else
        x_new(ptr_bin)=mean(temp_x);
        y_new(ptr_bin)=mean(temp_y);
        yerr_new(ptr_bin)=sqrt(sum(temp_yerr_sq))/length(temp_yerr_sq);
        temp_x=[x(k)];
        temp_y=[y(k)];
        temp_yerr_sq=[yerr(k)^2];
        ptr_bin=ptr_bin+1;
    end
end
% Last point
x_new(ptr_bin)=mean(temp_x);
y_new(ptr_bin)=mean(temp_y);
yerr_new(ptr_bin)=sqrt(sum(temp_yerr_sq))/length(temp_yerr_sq);
        
        
data_new=[x_new,y_new,yerr_new];
varargout{1}=data_new;
return
    
    
